// 3、在MovieSpider中创建服务，访问 http://localhost:8081/时，
// 可以打开页面,如图所示，
// 该页面中获取电影数据列表的请求接口为
// http://localhost:8081/getlist,
// 请求该接口时，服务端将爬取到的电影数据响应到页面中，显示到页面上。


const https    = require('https'),
	  fs      = require('fs'),
	  request = require('request'),
	  url     = require('url'),
      cheerio = require('cheerio'),
      log     = console.log,
	  qs = require('querystring'),
      print   = require('util').debuglog('dev');
var addr    = 'https://maoyan.com/films?showType=3';
addr = url.parse(addr);
addr.headers = {
    "User-Agent":'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36',
    "Cookie": 'uuid_n_v=v1; uuid=3DC245F01E6E11EBB8CBADD989F35CE05CFA6B8CF6974A5789977922B03FE4B4; _csrf=28815b25213a935454b951f74c1b8605c7885659a4f83e55c7f3c56c565f5173; Hm_lvt_703e94591e87be68cc8da0da7cbd0be2=1604474443; Hm_lpvt_703e94591e87be68cc8da0da7cbd0be2=1604474443; _lxsdk_cuid=175922123a7c8-0722019e3dfbc2-5313f6f-144000-175922123a78f; _lxsdk=3DC245F01E6E11EBB8CBADD989F35CE05CFA6B8CF6974A5789977922B03FE4B4; __mta=216407593.1604474449712.1604474449712.1604474449712.1; _lxsdk_s=175922123a9-c72-cb6-870%7C%7C3',
    "Sec-Fetch-Dest": "document",
    "Sec-Fetch-Mode": "navigate",
    "Sec-Fetch-Site": "cross-site",
    "Sec-Fetch-User": '?1',
    "Upgrade-Insecure-Requests": "1"
}
var list = [];
https.get(addr, (res) => {
  let result = '';
  res.on('data', (data) => {
    result += data.toString('utf8');   
  });
  res.on('end', () => {
    let $ = cheerio.load(result);
	//console.log($('body').find('dd').length);
    $('body').find('dd').each(function(index){
      let movieName = $(this).find('dd>.movie-item-title>a').text();
	  let movieId = $(this).find('dd>.movie-item-title>a').attr('href');
	  movieId = movieId.split('/');
	  let movieRange = $(this).find('dd>.channel-detail-orange>.integer').text();
	  if(movieRange === '')
		movieRange = $(this).find('dd>.channel-detail-orange').text();
	  else 
		movieRange += $(this).find('dd>.channel-detail-orange>.fraction').text();
	  var obj = new Object();
	  obj.movieId = movieId[2];
	  obj.movieName = movieName;
	  obj.movieRange = movieRange;
	  list[index] = obj;
    });
	console.log(list);
	list = JSON.stringify(list);
	console.log(list);
  });
});
var http = require('http');
var html = fs.readFileSync('./index.html');
http.createServer((req, res) => {
	if(req.url === '/') {
		res.end(html);
	}
	if(req.url === '/getlist') {
		res.end(list);
	}
}).listen(8081);
